package com.ssmtest.test.Controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ssmtest.test.Controller.utils.R;
import com.ssmtest.test.Pojo.User;
import com.ssmtest.test.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping
    public R getAllUser()
    {
        R r=new R();
        r.setFlag(true);
        r.setData(userService.list(null));

        return r ;
    }
    @PostMapping
    public R save(@RequestBody User user) throws IOException {
        R r=new R();
        r.setFlag(userService.save(user));
        r.setData(null);
        return r ;
    }
    @PutMapping
    public R updateUser(@RequestBody User user)
    {
        R r=new R();
        r.setFlag( userService.update(user,null));
        r.setData(null);
        return  r;
    }
    @DeleteMapping("{id}")
    public R deleteUser(@PathVariable Long id)
    {
        R r=new R();
        r.setFlag(userService.removeById(id) );
        r.setData(null);
        return  r;
    }
    @GetMapping("{id}")
    public R getByid(@PathVariable Long id)
    {
        R r=new R();
        r.setFlag(true);
        r.setData( userService.getById(id));
        System.out.println("chailong");
        return  r;
    }
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,User user){
        IPage<User> page=userService.getPage(currentPage,pageSize,user);
        //如果当前页面值大于总页面值，重新执行查询操作，使用最大页面值
        if(currentPage>page.getPages()){
            page=userService.getPage((int)page.getPages(),pageSize,user);
        }
        R r=new R();
        r.setData(page);
        r.setFlag(true);
        return r;
    }
}
